// pages/canteen/uploadfool/uploadfool.js
import Toast from '@vant/weapp/toast/toast';

let meal_name = ""
let meal_num = ""
let meal_price = ""
let meal_detail = ""
let meal_img = ""
let meal_status = false

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList2: [],
    camera: ['album', 'camera'],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if(!wx.getStorageSync('login')) {
      wx.redirectTo({
        url: '/pages/canteen/login/login',
      })
    }
  },
  
  onClickLeft() {
    wx.navigateBack()
  },

  afterRead(event) {
    var file  = event.detail;
    this.setData({
      file: file
    })
    
  },

  onChange(event) {
    console.log(event)
    var that = this;
    if(event.currentTarget.id=="name") {
      if(event.detail.length == 0) {
        that.setData({
          nameMsg: "饭菜名不能为空"
        })
      }else {
        that.setData({
          nameMsg: "",
        })
        meal_name = event.detail
      }
    }else if(event.currentTarget.id=="count"){
      if(event.detail.length == 0) {
        that.setData({
          countMsg: "数量不能为空"
        })
      }else {
        that.setData({
          countMsg: ""
        })
        meal_num = event.detail
      }
    } else if(event.currentTarget.id=="price") {
      if(event.detail.length == 0) {
        that.setData({
          meal_price: "价格不能为空"
        })
      }else {
        that.setData({
          priceMsg: ""
        })
        meal_price = event.detail
      }
    } else { // 饭菜描述暂时不做处理
      
    }
  },

  
  formSubmit (e) {
    let that = this;
    let value = e.detail.value
    const { fileList2 = [] } = this.data;
    
    if(fileList2.length==0 || fileList2[0].status=="uploading") {
      Toast.fail('图片还未上传成功，请等待');
    } else {
      if(value.name.length==0 || value.count.length==0 || value.price.length==0) {

        if(value.name.length==0) {
          that.setData({
            nameMsg: "饭菜名不能为空"
          })
        } else {
          meal_name = value.name
        }
    
        if(value.count.length==0) {
          that.setData({
            countMsg: "饭菜数量必须填"
          })
        } else {
          meal_num = value.count
        }
    
        if(value.price.length==0){
          that.setData({
            priceMsg: "价格不能为空"
          })
        } else {
          meal_price = value.price
        }
      } else {
        if(value.intro.length==0){
          meal_detail = "我是好吃的饭"
        } else {
          meal_detail = value.price
        }

        wx.cloud.callFunction({
          name: 'lu',
          data: {
            action: 'addmeal',
            meal_name: meal_name,
            meal_num: meal_num,
            meal_price: meal_price,
            meal_detail: meal_detail,
            meal_img: meal_img,
            meal_status: meal_status,
            window_id: wx.getStorageSync('window_id'),
            canteen_id: wx.getStorageSync('canteen_id')
          },
          success(res) {
            console.log("云函数增加数据成功",res)
            wx.redirectTo({
              url: '/pages/canteen/index/index',
            })
          },
          fail(res) {
            console.log("函数增加数据失败",res)
          }
        })
      }
    }
  },

  // 点击预览的x号
  deleteImg(event) {
    // 页面删除
    const delIndex = event.detail.index
    const { fileList2 } = this.data
    fileList2.splice(delIndex, 1)
    this.setData({
      fileList2
    })
    meal_img = ""
    // 云存储删除
    var fileID = this.data.fileID;
    this.deleteCloudSave(fileID)
  },

  deleteCloudSave(fileID) {
    wx.cloud.deleteFile({
      fileList: [fileID],
      success: res => {
        // handle success
        console.log(res.fileList)
      },
      fail: console.error
    })
  },

    // 点击上传图片后的状态
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    const { fileList2 = [] } = this.data;
    fileList2.push({})
    fileList2[0].status='uploading'
    this.setData({ fileList2 });
    this.uploadImage(file.url);
  },

  // 上传到云开发的存储中
  uploadImage(fileURL) {
    var that = this
    wx.cloud.uploadFile({
      cloudPath:new Date().getTime()+'.png', // 上传至云端的路径
      filePath: fileURL, // 小程序临时文件路径
      success: res => {
        //获取图片的http路径
        that.addImagePath(res.fileID)
        that.setData({
          fileID: res.fileID
        })
      },
      fail: console.error
    })
  },

  // 获取图片上传后的url路径
  addImagePath(fileId) {
    var that = this
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID:fileId
      }],
      success: res => {
        console.log(res)
        meal_img = res.fileList[0].tempFileURL
        const { fileList2 = [] } = that.data;
        fileList2[0].url= meal_img
        fileList2[0].status= 'done'
        that.setData({ fileList2 });
      },
      fail: console.error
    })
  },
})